class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int m = grid.size(), n = grid[0].size();
        auto dfs = [&] (this auto& dfs, int x, int y) {
            if(x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != '1')
                return;
            
            grid[x][y] = '0';
            dfs(x + 1, y);
            dfs(x, y + 1);
            dfs(x - 1, y);
            dfs(x, y - 1);
        }; 

        int ans = 0;
        for(int i = 0; i < m; ++i)
        {
            for(int j = 0; j < n; ++j)
            {
                if(grid[i][j] == '1')
                {
                    ++ans;
                    dfs(i, j);
                }
            }
        }
        return ans;
    }
};
